const Promise = require('bluebird');

/**
 * @api {get} /api/admin/v1/goodses/browse 商品列表
 * @apiGroup AdminGoodses
 * @apiDescription 商品管理-商品列表
 * @apiPermission 管理员(查看商品权限)
 * @apiVersion 1.0.0
 *
 * @apiUse apiBrowseParams
 * @apiParam {String}   [module]            模块
 * @apiParam {String}   [brand]             品牌
 * @apiParam {String}   [origin]            地区
 * @apiParam {Number}   [feature]           推荐 [dict.boolean]
 * @apiParam {String}   [status]            状态
 *
 * @apiUse apiBrowseResult
 */
exports.browse = function ({query}, {modelsData: {Categories, Goodses}, modelsData: {}, controller}) {
    let pagination = controller.pagination({
        params: query,
        filters: ['leafCatId', 'userType', 'sellerId', 'isNew', 'isHot', 'isJhs', 'isTqg', 'isPP'],
        likes: ['title', 'auctionId', 'activityId', 'sources']
    });
    return Promise.resolve().then(function () {
        let {category_id} = query;
        if (category_id && category_id != 'all') {
            return Categories.findOne({where: {id: category_id}}).then(function (category) {
                if (category && category.leafCatIds) {
                    pagination.where.leafCatId = JSON.parse(category.leafCatIds);
                }
            });
        }
    }).then(function () {
        return Goodses.findAndCountAll(pagination);
    });
}

/**
 * @api {get} /api/admin/v1/goodses/load 商品详情
 * @apiGroup AdminGoodses
 * @apiDescription 商品管理-商品详情
 * @apiPermission 管理员(查看商品权限)
 * @apiVersion 1.0.0
 *
 * @apiParam {Number}   id             编号
 * @apiParam {Number}   toggle         关联数据 [2(进价), 3(关联商品)]
 *
 * @apiUse apiLoadResult
 */
exports.load = function ({query}, {modelsData: {Goodses}, modelsData: {}}) {
    let {id} = query;
    return Goodses.findOne({where: {id: id}});
}


/**
 * @api {post} /api/admin/v1/goodses/add 商品添加
 * @apiGroup AdminGoodses
 * @apiDescription 商品管理-商品添加
 * @apiPermission 管理员(添加商品权限)
 * @apiVersion 1.0.0
 *
 * @apiParam {Number}   store_id            店铺编号
 * @apiParam {Number}   category_id         类别编号
 * @apiParam {String}   name                商品名
 * @apiParam {String}   [label]             标签
 * @apiParam {Number}   [sales]             销量
 * @apiParam {Number}   [order_by]          排序
 * @apiUse apiParamGoodses
 *
 * @apiUse apiSuccessResult
 */
exports.add = function ({body, user_id}, {modelsData: {Goodses, Coupons}, search: {searchEnable, goodsesSearch}, spider, config}) {
    let {auctionId, activityId, intro} = body;
    if (!auctionId || !activityId) {
        return {success: false, message: '参数错误'};
    }
    return spider.getGoodsByAuctionId({id: auctionId}).then(function (goods) {
        if (!goods) {
            return {success: false, message: '获取商品失败'};
        }
        return Coupons.findOne({where: {activity_id: activityId}}).then(function (oldCoupon) {
            if (oldCoupon) {
                return {success: false, message: '优惠券已经存在'};
            }
            return spider.captureCoupon({activity_id: activityId, goods_id: auctionId}).then(function (result) {
                if (!result.success || !result.data) {
                    return {success: false, message: '获取优惠券失败'};
                }
                let coupon = result.data;
                coupon.activity_id = activityId;
                coupon.seller_id = goods.sellerId;
                coupon.goodses_ids = auctionId;
                coupon.is_hidden = 1;
                coupon.is_enable = 1;
                coupon.sources = 'pyl';
                return Coupons.create(coupon).then(function () {
                    if (goods.record) {
                        console.error('商品已存在，成功添加优惠券');
                        return {success: true, message: '商品已存在，成功添加优惠券'};
                    }

                    goods.activityId = coupon.activity_id;
                    goods.quanAmount = coupon.quan_amount;
                    goods.quanPrice = (parseFloat((goods.zkPrice - (coupon.quan_amount || 0)).toFixed(2)) || 0).toFixed(2);
                    goods.intro = intro;
                    if (goods.quanPrice <= 3) {
                        goods.is30 = 1;
                    }
                    if (goods.quanPrice <= 10) {
                        goods.is99 = 1;
                    }
                    if (goods.quanPrice <= 20) {
                        goods.is199 = 1;
                    }
                    goods.sources = 'pyl';
                    goods.features = 'pyl';
                    goods.isNew = 1;

                    return Goodses.create(goods).then(function (newGoods) {
                        if (searchEnable) {
                            goodsesSearch.index(newGoods);
                        }
                        return {success: true};
                    });
                });
            });
        });
    });
}

/**
 * @api {post} /api/admin/v1/goodses/edit 商品编辑
 * @apiGroup AdminGoodses
 * @apiDescription 商品管理-商品编辑
 * @apiPermission 管理员(编辑商品权限)
 * @apiVersion 1.0.0
 *
 * @apiParam {Number}   id                  编号
 * @apiParam {Number}   [category_id]       类别编号
 * @apiParam {String}   [name]              商品名
 * @apiParam {String}   [label]             标签
 * @apiParam {Number}   [sales]             销量
 * @apiParam {Number}   [order_by]          排序
 * @apiUse apiParamGoodses
 *
 * @apiUse apiSuccessResult
 */
exports.edit = function ({body, user_id}, {modelsData: {Goodses}}) {
    let {id} = body;
    delete body.id;
    return Goodses.update(body, {where: {id: id}}).then(function (result) {
        if (!result[0]) {
            return {success: false};
        }
        return Goodses.findOne({where: {id: id}}).then(function (goods) {
            return {success: true, data: goods};
        });
    });
}

/**
 * @api {post} /api/admin/v1/goodses/delete 商品删除
 * @apiGroup AdminGoodses
 * @apiDescription 商品管理-商品删除
 * @apiPermission 管理员(删除商品权限)
 * @apiVersion 1.0.0
 *
 * @apiParam {Number}   store_id                   店铺编号
 * @apiParam {Number}   id                         编号
 *
 * @apiUse apiSuccessResult
 */
exports.delete = function ({body, user_id}, {modelsData: {Goodses, RemoveGoodses}, search: {searchEnable, goodsesSearch}}) {
    let {id} = body;
    return Goodses.findOne({where: {id: id}}).then(function (goods) {
        if (!goods) {
            return {success: false, message: '未找到商品'};
        }
        return Goodses.destroy({where: {id: id}}).then(function () {
            goods.reasons = 'by_' + user_id;
            RemoveGoodses.create(goods);

            if (searchEnable) {
                goodsesSearch.delete(goods.id);
            }
            return {success: true};
        });
    });
}